package site.teamo.biu.net.common.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import site.teamo.biu.net.common.constant.ChannelAttributeKey;

import java.util.concurrent.atomic.AtomicLong;

public class SimpleTransferHandler extends ChannelInboundHandlerAdapter {

    private final String name;
    private final AtomicLong total;

    public SimpleTransferHandler(String name, AtomicLong total) {
        this.name = name;
        this.total = total;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof ByteBuf byteBuf) {
            total.getAndAdd(byteBuf.readableBytes());
        }
        ctx.channel().attr(ChannelAttributeKey.TARGET_CHANNEL).get().writeAndFlush(msg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel targetChannel = ctx.channel().attr(ChannelAttributeKey.TARGET_CHANNEL).get();
        if (targetChannel != null) {
            targetChannel.close();
        }
        ctx.channel().close();
    }

    @Override
    public String toString() {
        return name;
    }
}
